layui.define(['base'], function (exports) {
    var $ = layui.jquery, layer = layui.layer, $util=layui.common, $setting = layui.config,
        $http = layui.http, $common = layui.common;
    var $table = $('#table'), validator,
        $form = $('#myModal form'),
        $modal = $('#myModal');
    /**
     *  修改 添加 打开模态框
     */

    // 自定义
    jQuery.validator.addMethod('require-one', function (value, element) {
        return $('.require-one:checked').size() > 0;
    }, '<i class="fa fa-times-circle"></i>用户需要分配至少一个角色');
    // 手机号码验证
    jQuery.validator.addMethod("isMobile", function (value, element) {
        var length = value.length;
        var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
        return this.optional(element) || (length == 11 && mobile.test(value));
    }, "请正确填写您的手机号码");

    var openModal = function (e, value, row, index) {
        $form[0].reset();
        validator = validator || $form.validate({
                ignore: '.ignore',
                groups: {
                    checks: $.map($('.require-one'), function (e, i) {
                        return $(e).attr('name')
                    }).join(' ')
                },
                rules: {
                    username: {
                        required: true,
                        maxlength: 15
                    },
                    phone: {
                        required: true,
                        digits: true,
                        isMobile: true
                    },
                    email: {
                        email: true
                    },
                    password: {
                        required: true
                    },
                    seatid: {
                        digits: true
                    }
                },
                errorPlacement: function (error, element) {
                    if ($(element[0]).attr('class').indexOf('require-one') === 0) {
                        $('#roleError').html(error);
                    } else {
                        error.insertAfter(element);
                    }
                }
            });

        //rest form
        validator.resetForm();

        //加载所有角色
        $http.get($setting.config.role.list, {
            pageSize: 2000
        }).send(function (obj) {
            if (obj.code == '0') {
                var roleHtml = new Array();
                $.each(obj.data, function (index, item) {
                    roleHtml.push('<div class="checkbox inline">' +
                        '<input class="require-one" id="check-' + item.id + '" name="check-' + item.id + '" value="' + item.id + '" type="checkbox">' +
                        '<label for="check-' + item.id + '">' + item.name + '</label>' +
                        '</div> &nbsp;&nbsp;&nbsp;&nbsp;');
                });
                $('#role-area').html(roleHtml.join(""));
                if (row) {  //修改    填充数据
                    $form.validate().settings.ignore = 'input[name="password"]';
                    $modal.data('handler', 'update');
                    $('#myModalLabel').text('修改人员');
                    $('#label-password').text('密码设置');
                    $('#myModal input[name="password"]').attr('placeholder', '不修改请留空');
                    $('#myModal input[name="userId"]').val(row.userId);
                    $('#myModal input[name="seatid"]').val(row.seatid);
                    $('#myModal input[name="workno"]').val(row.workno);

                    $('#myModal input[name="username"]').val(row.username);
                    $('#myModal input[name="phone"]').val(row.phone);
                    $('#myModal input[name="email"]').val(row.email);
                    $('#myModal input[name="password"]').val(row.password);
                    $('#myModal textarea[name="description"]').val(row.description);
                    if (row.roleIds) {          //填充角色
                        $(row.roleIds.split(',')).each(function (index, item) {
                            $('#check-' + item).attr('checked', true);
                        });
                    }
                } else {
                    $form.validate().settings.ignore = '.ignore';
                    $modal.data('handler', 'create');
                    $('#label-password').html('<span style="color: red;">*</span>密码设置');
                    $('#myModalLabel').text('添加人员');
                    $('#myModal input[name="password"]').attr('placeholder', '密码设置');
                    $('#myModal input[name="userId"]').val(0);
                }
                $modal.modal({
                    keyboard: true
                });
            }
        });
    };

    /**
     * 提交按钮
     */
    $('#submit-btn').click(function () {
        if (validator.form()) {
            $form.ajaxSubmit({
                xhrFields: {        //跨域
                    withCredentials: true
                },
                crossDomain: true,
                type: 'post',
                data: {
                    roleIds: $.map($('.require-one:checked'), function (item) {
                        return $(item).val();
                    }).join(',')
                },
                url: $modal.data('handler') == 'create' ? $setting.getUri() + $setting.config.user.create : $setting.getUri() + $setting.config.user.update,
                success: function (obj) {
                    layer.msg(obj.message, {icon: obj.code == '0' ? 1 : 2});
                    if (obj.code == '0') {
                        $table.bootstrapTable('refresh');
                        $modal.modal('hide');
                    }
                }
            });
        }
    });

    // 初始化表格
    $table.bootstrapTable({
        url: $setting.getUri() + $setting.config.user.list,
        dataType: "json",
        ajaxOptions: {
            xhrFields: {        //跨域
                withCredentials: true
            },
            crossDomain: true
        },
        sidePagination: 'server',
        pagination: true,
        idField: 'userId',
        dataField: 'list',
        columns: [{
            field: 'userId',
            align: 'center',
            title: 'id'
        }, {
            field: 'username',
            align: 'center',
            title: '姓名'
        }, {
            field: 'roleNames',
            align: 'center',
            title: '分配角色'
        }, {
            field: 'teamName',
            align: 'center',
            title: '归属团队'
        }, {
            field: 'phone',
            align: 'center',
            title: '手机号码'
        }, {
            field: 'email',
            align: 'center',
            title: '邮箱地址'
        }, {
            field: 'createTime',
            align: 'center',
            title: '添加时间'
        }, {
            field: 'createUserName',
            align: 'center',
            title: '添加人'
        }, {
            title: '操作',
            align: 'center',
            formatter: function (value, row) {
                return '&nbsp;&nbsp;&nbsp;<a title="修改" class="edit auth user-edit" data-id="' + row.userId + '" style="color:#1ab394;cursor:pointer">修改</a>'
                    + '&nbsp;&nbsp;&nbsp;<a title="删除" class="remove auth user-del" data-id="' + row.userId + '" style="color:#1ab394;cursor:pointer">删除</a>';
            },
            events: {
                'click .edit': openModal,
                'click .remove': function (e, value, row, index) {
                    layer.confirm('确认删除此条数据吗？', {
                        icon: 2,
                        title: ['提示', 'font-size:15px;text-align:left;padding-left: 10px;'],
                        btn: ['确定', '取消'],          //按钮
                        skin: 'layui-layer-molv'
                    }, function () {
                        $http.post($setting.config.user.delete, {
                            userId: row.userId
                        }).send(function (obj) {
                            layer.msg(obj.message, {icon: obj.code == '0' ? 1 : 2});
                            if (obj.code == '0') {
                                $table.bootstrapTable('refresh');
                                $modal.modal('hide');
                            }
                        });
                    });
                }
            }
        }],
        pageSize: 20,
        pageList: [10, 20, 50],
        queryParams: function (params) {
            return {
                username: $('#search').val().trim(),
                pageIndex: params.offset / params.limit + 1,
                pageSize: params.limit //页面大小
            };
        },
        responseHandler: $util.fn.table.response,
        onLoadSuccess: $util.fn.table.onLoadSuccess,
        onLoadError: $util.fn.table.onLoadError,
        onClickRow: function (row, $element) {
            $element.siblings().css('background-color', 'white');
            $element.css("background-color", "rgb(243, 247, 249)");
        }
    });

    /**
     * 添加 按钮
     */
    $('#btn_add').on('click', openModal);

    /**
     * 查询
     */
    $('#search').keypress(function (event) {
        if (event.keyCode == 13) {
            layer.load();
            $table.bootstrapTable('selectPage', 1);
        }
    });
    /**
     * 查询
     */
    $('.glyphicon-search').on('click', function () {
        layer.load();
        $table.bootstrapTable('selectPage', 1);
    });

    exports('../app/admin/admin', {});
});